package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.bean.SysDept;
import com.zzw.springboot.mapper.SysDeptMapper;
import com.zzw.springboot.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门服务实现类
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Autowired
    private SysDeptMapper deptMapper;

    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysDept::getIsDeleted, 0);
        
        if (dept != null) {
            // 根据部门名称模糊查询
            if (StringUtils.hasText(dept.getName())) {
                queryWrapper.like(SysDept::getName, dept.getName());
            }
            // 根据部门状态查询
            if (dept.getStatus() != null) {
                queryWrapper.eq(SysDept::getStatus, dept.getStatus());
            }
        }
        
        // 按父ID和排序字段升序排列
        queryWrapper.orderByAsc(SysDept::getParentId);
        queryWrapper.orderByAsc(SysDept::getSort);
        
        return list(queryWrapper);
    }

    @Override
    public List<SysDept> selectDeptListExcludeChild(Integer deptId) {
        // 查询所有部门
        List<SysDept> allDeptList = selectDeptList(new SysDept());
        // 查询需要排除的部门及其子部门
        List<SysDept> excludeChildList = deptMapper.selectChildrenDeptById(deptId);
        
        // 将需要排除的部门ID添加到集合中
        Set<Integer> excludeDeptIds = new HashSet<>();
        excludeDeptIds.add(deptId); // 排除自己
        excludeChildList.forEach(dept -> excludeDeptIds.add(dept.getId()));
        
        // 过滤不在排除列表中的部门
        return allDeptList.stream()
                .filter(dept -> !excludeDeptIds.contains(dept.getId()))
                .collect(Collectors.toList());
    }

    @Override
    public List<SysDept> selectDeptTreeList(SysDept dept) {
        // 获取所有部门列表
        List<SysDept> depts = selectDeptList(dept);
        
        // 按照父ID分组
        Map<Integer, List<SysDept>> parentIdMap = depts.stream()
                .collect(Collectors.groupingBy(SysDept::getParentId));
        
        // 构建树结构
        List<SysDept> returnList = new ArrayList<>();
        for (SysDept d : depts) {
            // 如果是根节点（父ID为0或null）
            if (d.getParentId() == null || d.getParentId() == 0) {
                returnList.add(d);
            }
            
            // 设置子部门
            List<SysDept> children = parentIdMap.get(d.getId());
            if (children != null && !children.isEmpty()) {
                d.setChildren(children);
                d.setHasChildren(true);
            } else {
                d.setHasChildren(false);
            }
        }
        
        return returnList;
    }

    @Override
    public SysDept selectDeptById(Integer deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(Integer deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysDept::getParentId, deptId);
        queryWrapper.eq(SysDept::getIsDeleted, 0);
        
        return count(queryWrapper) > 0;
    }

    @Override
    public boolean checkDeptExistUser(Integer deptId) {
        return deptMapper.checkDeptExistUser(deptId) > 0;
    }

    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Integer deptId = dept.getId() == null ? 0 : dept.getId();
        
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysDept::getName, dept.getName());
        queryWrapper.eq(SysDept::getParentId, dept.getParentId());
        queryWrapper.eq(SysDept::getIsDeleted, 0);
        queryWrapper.ne(deptId > 0, SysDept::getId, deptId);
        
        return count(queryWrapper) == 0;
    }

    @Override
    @Transactional
    public boolean insertDept(SysDept dept) {
        if (dept.getParentId() == null) {
            dept.setParentId(0); // 如果父ID为空，则默认为根节点
            dept.setAncestors("0"); // 根节点的祖先为0
        } else {
            // 获取父部门
            SysDept parentDept = deptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null) {
                dept.setAncestors(parentDept.getAncestors() + "," + parentDept.getId());
            }
        }
        
        dept.setCreateTime(new Date());
        return save(dept);
    }

    @Override
    @Transactional
    public boolean updateDept(SysDept dept) {
        // 获取旧的部门信息
        SysDept oldDept = deptMapper.selectDeptById(dept.getId());
        
        // 如果父部门变更，则需要更新所有子部门的ancestors
        if (dept.getParentId() != null && !dept.getParentId().equals(oldDept.getParentId())) {
            // 获取新的父部门信息
            SysDept parentDept = deptMapper.selectDeptById(dept.getParentId());
            String newAncestors = "0";
            if (parentDept != null) {
                newAncestors = parentDept.getAncestors() + "," + parentDept.getId();
            }
            
            dept.setAncestors(newAncestors);
            // 更新子部门的祖先
            updateChildrenAncestors(dept.getId(), newAncestors, oldDept.getAncestors());
        }
        
        dept.setUpdateTime(new Date());
        return updateById(dept);
    }

    /**
     * 更新子部门的祖先
     */
    private void updateChildrenAncestors(Integer deptId, String newAncestors, String oldAncestors) {
        // 查询所有子部门
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        
        if (!children.isEmpty()) {
            List<SysDept> updateList = new ArrayList<>();
            for (SysDept child : children) {
                // 替换祖先部分
                String childAncestors = child.getAncestors().replace(oldAncestors, newAncestors);
                child.setAncestors(childAncestors);
                updateList.add(child);
            }
            
            // 批量更新
            if (!updateList.isEmpty()) {
                deptMapper.updateDeptChildren(updateList);
            }
        }
    }

    @Override
    public boolean deleteDeptById(Integer deptId) {
        // 检查是否能够删除
        if (hasChildByDeptId(deptId)) {
            throw new RuntimeException("存在下级部门,不允许删除");
        }
        if (checkDeptExistUser(deptId)) {
            throw new RuntimeException("部门存在用户,不允许删除");
        }
        
        // 执行逻辑删除
        SysDept dept = new SysDept();
        dept.setId(deptId);
        dept.setIsDeleted(1);
        dept.setUpdateTime(new Date());
        
        return updateById(dept);
    }

    @Override
    public Map<String, Object> getCheckedDeptList(Integer roleId) {
        // 获取所有部门列表
        List<SysDept> deptList = selectDeptList(new SysDept());
        // 获取角色已选择的部门ID列表
        List<Integer> checkedDeptIds = deptMapper.selectDeptListByRoleId(roleId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("depts", deptList);
        result.put("checkedDeptIds", checkedDeptIds);
        
        return result;
    }
} 